<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { aliPay, createOrder } from "@/api/user";
import { getUserCouponsByStatus } from "@/api/userCoupon.js";

interface Seat {
  row: string;
  col: number;
  isAvailable: boolean;
  isSelected: boolean;
}

interface OrderData {
  movieId: string | number;
  movieName: string;
  moviePoster: string;
  score: string;
  duration: string;
  type: string;
  actors: string;
  scheduleId: number;
  time: string;
  hall: string;
  price: string | number;
  selectedSeats: Seat[];
  totalPrice: number;
}

interface Coupon {
  userCoupon: {
    userCouponId: number;
    userId: number;
    couponId: number;
    status: number;
    obtainTime: string;
  };
  coupon: {
    couponId: number;
    couponName: string;
    couponValue: number;
    minSpend: number;
    validStart: string;
    validEnd: string;
    description: string;
  };
}

const orderData = ref<OrderData>({} as OrderData);
const route = useRoute();
const router = useRouter();

// 倒计时功能
const minutes = ref(15);
const seconds = ref(0);
let countdownTimer = null;
const isProcessingPayment = ref(false);

// 优惠券相关变量
const coupons = ref<Coupon[]>([]);
const selectedCoupon = ref<Coupon | null>(null);
const serviceFee = ref(5); // 服务费默认5元

// 计算实付款
const finalPayment = computed(() => {
  const ticketPrice = Number(orderData.value.totalPrice) || 0;
  const couponAmount = selectedCoupon.value
    ? Number(selectedCoupon.value.coupon.couponValue) || 0
    : 0;

  // 实付款 = 票价 + 服务费 - 优惠券金额（不小于0）
  const result = Math.max(ticketPrice + serviceFee.value - couponAmount, 0);
  console.log(`计算实付款: 票价(${ticketPrice}) + 服务费(${serviceFee.value}) - 优惠券(${couponAmount}) = ${result}`);
  return result;
});

// 格式化座位显示
const formatSeats = () => {
  const seats = orderData.value.selectedSeats
    ?.map((seat) => `${seat.row}${seat.col}`)
    .join(", ") || "";
  console.log("格式化座位显示:", seats);
  return seats;
};

// 格式化座位坐标（用于创建订单）
const formatSeatCoordinates = () => {
  const coordinates = orderData.value.selectedSeats
    ?.map((seat) => `${seat.row}${seat.col}`)
    .join(",") || "";
  console.log("格式化座位坐标:", coordinates);
  return coordinates;
};

// 生成订单号
const generateOrderNumber = () => {
  const timestamp = new Date().getTime();
  const random = Math.floor(Math.random() * 1000);
  const orderNumber = `ORDER${timestamp}${random}`;
  console.log("生成订单号:", orderNumber);
  return orderNumber;
};



// 获取可用优惠券
const fetchAvailableCoupons = async () => {
  try {
    const userId = localStorage.getItem("userId");
    console.log("获取可用优惠券 - 用户ID:", userId);
    if (userId) {
      // 获取状态为1的未使用优惠券
      console.log("调用getUserCouponsByStatus接口，参数: userId=", userId, "status=1");
      const res = await getUserCouponsByStatus(userId, 1);
      console.log("获取可用优惠券响应:", res);
      
      if (res.data && res.data.data) {
        coupons.value = res.data.data;
        console.log("可用优惠券列表:", coupons.value);
      } else {
        console.warn("优惠券接口返回格式异常:", res);
        coupons.value = [];
      }
    }
  } catch (e) {
    console.error("获取优惠券异常:", e);
  }
};

// 开始倒计时
onMounted(() => {
  console.log("支付页面初始化 - 路由参数:", route.query);
  console.log(route.query.orderData)
  if (route.query.orderData) {
    try {
      orderData.value = JSON.parse(route.query.orderData as string);
      console.log("解析到的订单数据:", orderData.value);
    } catch (error) {
      console.error("解析orderData失败:", error);
      alert("订单信息解析失败，请重新操作");
      router.push("/cinemaDetail");
    }
  } else {
    console.warn("未获取到orderData参数");
    alert("订单信息缺失，请重新操作");
    router.push("/cinemaDetail");
  }

  // 获取优惠券
  fetchAvailableCoupons();

  // 倒计时逻辑
  countdownTimer = setInterval(() => {
    console.log(`倒计时: ${minutes.value}:${seconds.value}`);
    if (seconds.value === 0) {
      if (minutes.value === 0) {
        clearInterval(countdownTimer);
        console.log("订单超时，自动取消");
        alert("订单已超时，请重新下单");
        router.push("/cinemaDetail");
        return;
      }
      minutes.value--;
      seconds.value = 59;
    } else {
      seconds.value--;
    }
  }, 1000);
});

// 清除倒计时
onUnmounted(() => {
  if (countdownTimer) {
    console.log("页面卸载，清除倒计时");
    clearInterval(countdownTimer);
  }
});

const goBackToSeat = () => {
  console.log("返回选座页面，携带参数:", {
    movieId: orderData.value.movieId,
    movieName: orderData.value.movieName,
    moviePoster: orderData.value.moviePoster,
    score: orderData.value.score,
    duration: orderData.value.duration,
    type: orderData.value.type,
    actors: orderData.value.actors,
    scheduleId: orderData.value.scheduleId,
    time: orderData.value.time,
    hall: orderData.value.hall,
    price: orderData.value.price,
  });
  
  router.push({
    path: "/seatSelection",
    query: {
      movieId: orderData.value.movieId,
      movieName: orderData.value.movieName,
      moviePoster: orderData.value.moviePoster,
      score: orderData.value.score,
      duration: orderData.value.duration,
      type: orderData.value.type,
      actors: orderData.value.actors,
      scheduleId: orderData.value.scheduleId,
      time: orderData.value.time,
      hall: orderData.value.hall,
      price: orderData.value.price,
    },
  });
};

const checkLoginStatus = () => {
  const token = localStorage.getItem("token");
  const userId = localStorage.getItem("userId");
  
  console.log("检查登录状态 - token存在:", !!token, "userId存在:", !!userId);

  if (!token || !userId) {
    // 保存当前页面信息，登录后跳转回来
    const currentPath = route.path;
    const currentQuery = JSON.stringify(route.query);
    console.log("未登录，保存跳转信息 - path:", currentPath, "query:", currentQuery);
    
    localStorage.setItem("redirectPath", currentPath);
    localStorage.setItem("redirectQuery", currentQuery);

    // 跳转到登录页
    router.push("/login");
    return false;
  }
  return true;
};

// 完成支付
const completePayment = async () => {
  // 先检查登录状态
  console.log("开始支付流程 - 检查登录状态");
  if (!checkLoginStatus()) {
    console.log("未通过登录检查，终止支付流程");
    return;
  }

  if (!orderData.value) {
    alert("订单信息有误，请重新选择");
    console.error("订单信息为空，无法创建订单");
    return;
  }

  try {
    isProcessingPayment.value = true;
    console.log("开始创建订单...");

    // 获取用户ID
    const userId = localStorage.getItem("userId");
    if (!userId) {
      alert("用户信息获取失败，请重新登录");
      console.error("userId为空，无法创建订单");
      router.push("/login");
      return;
    }

    // 计算票数
    const ticketCount = orderData.value.selectedSeats?.length || 0;
    console.log("票数计算:", ticketCount);
    
    // 计算优惠券金额
    const couponAmount = selectedCoupon.value
      ? Number(selectedCoupon.value.coupon.couponValue)
      : 0;
    console.log("优惠券金额:", couponAmount);

    // 构建创建订单的参数（符合后端要求的格式）
    const orderInfo = {
      orderBase: {
        scheduleId: Number(orderData.value.scheduleId),
        userId: Number(userId),
        orderTime: new Date().toISOString().slice(0, 19), // 格式化为yyyy-MM-ddTHH:mm:ss
        originalPrice: Number(orderData.value.price) * ticketCount, // 原价 = 单价 * 票数
        finalPrice: finalPayment.value, // 使用计算后的实付款
        userCouponId: selectedCoupon.value
          ? selectedCoupon.value.userCoupon.userCouponId
          : null,
        couponAmount: couponAmount,
        serviceFee: serviceFee.value,
        seatCoordinates: formatSeatCoordinates(), // 座位坐标，如"A1,A2"
        orderNumber: generateOrderNumber(), // 订单编号
      },
      orderDetails: [
        {
          scheduleId: Number(orderData.value.scheduleId),
          movieName: orderData.value.movieName,
          movieImage: orderData.value.moviePoster,
          moviePrice: Number(orderData.value.price), // 单价
          ticketCount: ticketCount, // 票数
          statues: 0, // 初始状态
        },
      ],
    };

    console.log("创建订单参数:", orderInfo);

    // 创建订单
    console.log("调用createOrder接口...");
    const orderRes = await createOrder(orderInfo);
    console.log("创建订单响应:", orderRes);

    // 根据后端实际返回结构调整判断逻辑
    if (orderRes.data.code === 200) {
      const createdOrder = orderRes.data.data;
      console.log("订单创建成功:", createdOrder);

      // 跳转到订单详情页，携带优惠券信息
      const redirectData = {
        ...orderData.value,
        orderId: createdOrder.orderId,
        orderNumber: createdOrder.orderNumber,
        originalPrice: createdOrder.originalPrice,
        totalPrice: orderData.value.totalPrice,
        ticketCount: ticketCount,
        serviceFee: serviceFee.value,
         couponAmount: selectedCoupon.value ? selectedCoupon.value.coupon.couponValue : 0,
        couponName: selectedCoupon.value ? selectedCoupon.value.coupon.couponName : "",
        finalPrice: finalPayment.value,
      };
      console.log("跳转到订单详情页，携带数据:", redirectData);
      
      router.push({
        path: "/order-detail",
        query: {
          orderData: JSON.stringify(redirectData),
          moviePoster: orderData.value.moviePoster,
        },
      });
    } else {
      // 区分重复订单和其他错误
      let errorMsg;
      if (orderRes.data.code === 201) {
        // 重复订单使用data中的提示信息
        errorMsg = orderRes.data.data || "订单重复，请勿重复提交";
      } else {
        // 其他错误使用message或默认信息
        errorMsg = orderRes.data.message || "创建订单失败";
      }
      console.error(`创建订单失败 - code: ${orderRes.data.code}, 消息: ${errorMsg}`);
      throw new Error(errorMsg);
    }
  } catch (err) {
    console.error("创建订单失败", err);
    alert(err.message || "创建订单过程出错，请重试");
  } finally {
    isProcessingPayment.value = false;
    console.log("支付流程结束");
  }
};
</script>

<template>
  <!-- 模板内容不变 -->
  <div class="payment-page">
    <!-- 进度条 -->
    <div class="progress-bar">
      <div class="progress-container">
        <div class="progress-step active">1</div>
        <div class="progress-line active"></div>
        <span class="progress-text active">选座</span>
        <div class="progress-line active"></div>
        <div class="progress-step active">2</div>
        <div class="progress-line"></div>
        <span class="progress-text active">支付</span>
      </div>
    </div>

    <!-- 倒计时提醒 -->
    <div class="countdown-alert">
      <p>
        请在
        <span class="countdown-time"
          >{{ minutes }}:{{ seconds < 10 ? "0" + seconds : seconds }}</span
        >
        内完成支付，超时订单将自动取消
      </p>
    </div>

    <!-- 支付信息 -->
    <div class="payment-container">
      <!-- 电影信息 -->
      <div class="movie-details">
        <h3>订单信息</h3>

        <div class="movie-info-wrap">
          <img
            :src="orderData.moviePoster"
            :alt="orderData.movieName"
            class="movie-poster"
          />

          <div class="movie-info">
            <h4>{{ orderData.movieName }}</h4>
            <p>{{ orderData.type }} / {{ orderData.duration }}</p>
            <p>主演：{{ orderData.actors }}</p>
            <p>影院：星光国际影城（北京朝阳店）</p>
            <p>影厅：{{ orderData.hall }}</p>
            <p>场次：{{ orderData.time }}</p>
            <p>座位：{{ formatSeats() }}</p>
          </div>
        </div>

        <!-- 优惠券选择区域 -->
        <div class="coupon-section">
          <h3>选择优惠券</h3>
          <select v-model="selectedCoupon" class="coupon-select">
            <option value="">不使用优惠券</option>
            <option
              v-for="coupon in coupons"
              :key="coupon.userCoupon.userCouponId"
              :value="coupon"
            >
              ¥{{ coupon.coupon.couponValue }} - {{ coupon.coupon.couponName }}
              <span v-if="coupon.coupon.minSpend > 0"
                >(满{{ coupon.coupon.minSpend }}可用)</span
              >
            </option>
          </select>
        </div>
      </div>

      <!-- 支付信息 -->
      <div class="payment-info">
        <h3>支付信息</h3>

        <div class="price-detail">
          <p class="price-item">
            <span>票价 ({{ orderData.selectedSeats?.length || 0 }}张)</span>
            <span>¥{{ orderData.totalPrice }}</span>
          </p>
          <p class="price-item">
            <span>服务费</span>
            <span>¥{{ serviceFee }}</span>
          </p>
          <p class="price-item" v-if="selectedCoupon">
            <span>优惠券抵扣</span>
            <span class="discount"
              >-¥{{ selectedCoupon.coupon.couponValue }}</span
            >
          </p>
          <p class="total-price">
            <span>实付款</span>
            <span>¥{{ finalPayment }}</span>
          </p>
        </div>

        <div class="payment-buttons">
          <button @click="goBackToSeat" class="back-btn">返回选座</button>

          <button
            @click="completePayment"
            class="pay-btn"
            :disabled="isProcessingPayment"
          >
            {{ isProcessingPayment ? "处理中..." : "确认支付" }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style>
/* 样式内容不变 */
.payment-page {
  padding: 20px;
  width: 1200px;
}

.progress-bar {
  margin-bottom: 30px;
}

.progress-container {
  display: flex;
  align-items: center;
  max-width: 500px;
  margin: 0 auto;
}

.progress-step {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  background-color: #ddd;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.progress-step.active {
  background-color: #a2131d;
  color: white;
}

.progress-line {
  flex: 1;
  height: 2px;
  background-color: #ddd;
  margin: 0 10px;
}

.progress-line.active {
  background-color: #a2131d;
}

.progress-text {
  color: #999;
}

.progress-text.active {
  color: #a2131d;
  font-weight: bold;
}

.countdown-alert {
  background-color: #fff8e6;
  border: 1px solid #ffe8cc;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 30px;
}

.countdown-alert p {
  margin: 0;
  color: #e67700;
  font-size: 15px;
}

.countdown-time {
  font-weight: bold;
  color: #a2131d;
}

.payment-container {
  display: flex;
  gap: 30px;
}

.movie-details {
  flex: 1;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.movie-info-wrap {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.movie-poster {
  width: 120px;
  height: 160px;
  object-fit: cover;
  border-radius: 4px;
}

.movie-info {
  flex: 1;
}

.movie-info h4 {
  margin: 0 0 15px 0;
  font-size: 18px;
}

.movie-info p {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

/* 优惠券样式 */
.coupon-section {
  margin: 20px 0;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.coupon-select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-top: 10px;
  font-size: 14px;
}

.payment-info {
  flex: 0 0 350px;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.payment-info h3 {
  margin-top: 0;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.price-detail {
  margin-bottom: 30px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
}

.price-item .discount {
  color: #a2131d;
}

.total-price {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
  font-size: 16px;
  font-weight: bold;
  color: #a2131d;
}

.payment-buttons {
  display: flex;
  gap: 10px;
}

.back-btn {
  flex: 1;
  padding: 12px;
  background-color: white;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.back-btn:hover {
  background-color: #f5f5f5;
}

.pay-btn {
  flex: 1;
  padding: 12px;
  background-color: #a2131d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.pay-btn:hover:not(:disabled) {
  background-color: #8a1018;
}

.pay-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .payment-page {
    width: 100%;
  }

  .payment-container {
    flex-direction: column;
  }

  .payment-info {
    width: 100%;
    flex: none;
  }
}
</style>